package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.DictConsoleService;
import com.ibeetl.admin.console.service.UserConsoleService;
import com.ibeetl.admin.core.conf.PasswordConfig;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.util.AESUtil;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.TelentCard;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.web.query.InsuranceQuery;
import com.ibeetl.cms.web.query.MedicalCareQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

/**
 * 所有角色都能使用的 接口
 */
@Controller
public class CommonController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/common";

    @Autowired
    CorePlatformService platformService;

    @Autowired
    FileService fileService;

    @Autowired
    UserConsoleService userConsoleService;

    @Autowired
    private QuitService quitService;

    @Autowired
    private RentingService rentingService;

    @Autowired
    private DeclareLimitService declareLimitService;

    @Autowired
    private CoreUserService coreUserService;

    @Autowired
    private TelentCardService telentCardService;

    @Autowired
    private InsuranceService insuranceService;

    @Autowired
    private MedicalCareService medicalCareService;

    @Autowired
    private HighlevelTalentsService highlevelTalentsService;

    @Autowired
    private OutboundSubsidyService outboundSubsidyService;

    @Autowired
    private  DoctoralSubsidyService doctoralSubsidyService;

    @Autowired
    private PasswordConfig.PasswordEncryptService passwordEncryptService;

    @Autowired
    private DictConsoleService dictConsoleService;


    /**
     * 企业受理需要满足条件 20200507
     *
     * @param declarationType 数据库对应申报的表名
     * @return
     */
    @PostMapping(MODEL + "/acceptanceVaild.json")
    @ResponseBody
    public JsonResult acceptanceVaild(String declarationType) {
        //业务受理时间验证
        if(declareLimitService.isInTime(getIntType(declarationType),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        return JsonResult.success();
    }

    @GetMapping(MODEL + "/initChangePassword.do")
    public ModelAndView initChangePassword() {
        CoreUser user = platformService.getCurrentUser();
        ModelAndView view = new ModelAndView("/cms/common/initChangePassword.html");
        view.addObject("user", user);
        return view;
    }

    @GetMapping(MODEL + "/changePassword.do")
    public ModelAndView changePassword() {
        CoreUser user = platformService.getCurrentUser();
        ModelAndView view = new ModelAndView("/cms/common/changePassword.html");
        view.addObject("user", user);
        return view;
    }

    /**
     * 用户密码
     *
     * @return
     */
    @PostMapping(MODEL + "/changePassword.json")
    @ResponseBody
    public JsonResult changePassword(Long id, String password, String password_old) {
        //校验密码：只能输入8-16个字母+数字
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^(?=.{8,16})(?=.*[a-z])(?=.*\\d).*$");
        java.util.regex.Matcher match = pattern.matcher(password);
        if (password.length() < 8 || password.length() > 16) {
            return JsonResult.failMessage("长度在8-16位");
        } else if (!match.matches()) {
            return JsonResult.failMessage("新密码中必需含有数字和字母");
        }

        CoreUser user = platformService.getCurrentUser();
        String passwordOldEncrypt = passwordEncryptService.password(password_old);
        if (!passwordOldEncrypt.equals(user.getPassword())) {
            return JsonResult.failMessage("填写的原密码不准确");
        }
        if (user.getId() != id.longValue()) {
            return JsonResult.failMessage("没有权限");
        }
        userConsoleService.resetPassword(id, password);
        return JsonResult.success();
    }

    /**
     * 申报需要满足条件
     *
     * @param declarationType 数据库对应申报的表名
     * @return
     */
    @PostMapping(MODEL + "/notLeave.json")
    @ResponseBody
    public JsonResult notLeave(String declarationType) {
        CoreUser currentUser = platformService.getCurrentUser();

        InsuranceQuery insuranceQuery = new InsuranceQuery();
        MedicalCareQuery medicalCareQuery = new MedicalCareQuery();
        insuranceQuery.setUserid(currentUser.getId());
        medicalCareQuery.setUserid(currentUser.getId());

        Date date=new Date();//获取当前时间

        //获取当前申报年度-字典配置
        String yearStr = dictConsoleService.getDeclareYear();
        Integer year = null;
        if(StringUtils.isNotEmpty(yearStr)){
            year = Integer.parseInt(yearStr);
        }
        //站点经费资助、博士后在站补贴、博士后出站补贴、高层次人才奖励补贴
        if("site_funds".equals(declarationType) || "doctoral_subsidy".equals(declarationType)
                || "outbound_subsidy".equals(declarationType) || "highlevel_talents".equals(declarationType)){
            if(quitService.judgeYear(declarationType,currentUser.getId().intValue(),year)){
                return JsonResult.failMessage("您["+year+"]年度已申报,无法继续申报！");
            }
            JsonResult.success();
        }

        //员工离职状态 所有业务都不可操作
        if (!coreUserService.findUserById(currentUser.getCompanyId()) && 177 == currentUser.getOrgId()) {
            if("key_information".equals(declarationType)){
                return JsonResult.failMessage("离职状态无法申报关键信息变更！");
            }
            return JsonResult.failMessage("无法申报，您当前所在企业已删除或您当前为离职状态！");
        }

        //产业人才
        if("industrial_talents".equals(declarationType)){
            if(declareLimitService.isInTime(getIntType(declarationType),new Date())==0){
                return JsonResult.failMessage("不在业务申报时限，不可申报！");
            }
            if(quitService.judgeYear(declarationType,currentUser.getId().intValue(),year)){
                return JsonResult.failMessage("您["+year+"]年度已申报,无法继续申报！");
            }
            JsonResult.success();
        }

        //购房补贴
        if("buy_house_subsidies".equals(declarationType)){
            if(declareLimitService.isInTime(getIntType(declarationType),new Date())==0){
                return JsonResult.failMessage("不在业务申报时限，不可申报！");
            }
            if(quitService.talentCardIsNull(currentUser.getId().intValue()) == null){
                return JsonResult.failMessage("请先申报产业人才，生成产业人才卡后再行申报！");
            }
            if(quitService.talentCardGetScore(currentUser.getId().intValue()) < 30){
                return JsonResult.failMessage("产业人才卡积分不足30无法申报！");
            }
            JsonResult.success();
        }

        //技能提升奖励、专业技术提升奖励
        if("skill".equals(declarationType) || "professional_technology".equals(declarationType)){
            if(declareLimitService.isInTime(getIntType(declarationType),new Date()) == 0){
                return JsonResult.failMessage("不在业务申报时限，不可申报！");
            }
            if(quitService.talentCardIsNull(currentUser.getId().intValue()) == null){
                return JsonResult.failMessage("请先申报产业人才，生成产业人才卡后再行申报！");
            }
            if(quitService.judgeYear(declarationType,currentUser.getId().intValue(),year)){
                return JsonResult.failMessage("您["+year+"]年度已申报,无法继续申报！");
            }
            JsonResult.success();
        }

        //租房补贴
        if("renting".equals(declarationType)){
            if(declareLimitService.isInTime(getIntType(declarationType),new Date())==0){
                return JsonResult.failMessage("不在业务申报时限，不可申报！");
            }
            if(quitService.judgeYear(declarationType,currentUser.getId().intValue(),year)){
                return JsonResult.failMessage("您["+year+"]年度已申报,无法继续申报！");
            }
            if(rentingService.findMonth(currentUser.getId())>=36){
                return JsonResult.failMessage("您的申报月数已满36个月无法继续申报！");
            }
            JsonResult.success();
        }

        //健康体检、健康保险
        if( "medical_care".equals(declarationType)  || "insurance".equals(declarationType)){
            TelentCard telentCard = telentCardService.findCard(currentUser.getId());
            if(telentCard == null){
                return JsonResult.failMessage("请先申报产业人才，生成产业人才卡后再行申报！");
            }else if(StringUtils.isNotEmpty(telentCard.getLevel()) && !"A".equals(telentCard.getLevel())){
                return JsonResult.failMessage("您当前还不是A级产业人才，不符合医疗保健服务申请条件！");
            }

            if(quitService.judgeYear(declarationType,currentUser.getId().intValue(),year)){
                return JsonResult.failMessage("您["+year+"]年度已申报,无法继续申报！");
            }

            if(insuranceService.queryEmployeesCount(insuranceQuery) >= 5 || medicalCareService.queryEmployeesCount(medicalCareQuery) >= 5){
                return JsonResult.failMessage("每个人才只能申报5次");
            }

            //健康体检 - 每年12月申报
            if("medical_care".equals(declarationType) && date.getMonth()+1 != 12){
                return JsonResult.failMessage("申报日期为12月份");
            }
        }
        return JsonResult.success();
    }

    public static Integer getIntType(String declarationType) {
        switch (declarationType) {
            case "industrial_talents":
                return 1;
            case "preparatory_talent":
                return 2;
            case "buy_house_subsidies":
                return 3;
            case "skill":
                return 4;
            case "professional_technology":
                return 5;
            case "renting":
                return 6;
            case "doctoral_subsidy":
                return 7;
            case "outbound_subsidy":
                return 8;
            case "highlevel_talents":
                return 9;
            case "site_funds":
                return 10;
            case "quit":
                return 11;
            case "entry":
                return 12;
            case "key_information":
                return 13;
            case "medical_care":
                return 14;
            case "insurance":
                return 15;
            case "green_treatment":
                return 16;
        }
        return 0;
    }

    /*
     **入职申报条件
     */
    @PostMapping(MODEL + "/entry.json")
    @ResponseBody
    public JsonResult entry() {
        CoreUser currentUser = platformService.getCurrentUser();
        if (currentUser.getCompanyId() != 0) {
            return JsonResult.failMessage("该用户已经处于入职状态，不可再申报入职");
        }
        return JsonResult.success();
    }

    /*
     **离职职申报条件
     */
    @PostMapping(MODEL + "/quit.json")
    @ResponseBody
    public JsonResult quit() {
        CoreUser currentUser = platformService.getCurrentUser();
        // Integer year = Calendar.getInstance().get(Calendar.YEAR);//获取当前年度
        if (currentUser.getCompanyId() == 0) {
            return JsonResult.failMessage("您已离职,无法继续申报");
        }
        return JsonResult.success();
    }

    /*
     * 功能描述: 手动获取加密密码
     * @author liujun
     * @date 2019/12/24 10:22
     * @param
     * @return
     */
    public static void main(String[] args) {
        System.out.println(AESUtil.encrypt("1",AESUtil.PWD));
    }

}

